using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using GoogleGeocoder;

public partial class AddNewStore : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void addNewStoreButton_Click(object sender, EventArgs e)
    {
        string address = String.Format("{0}, {1}, {2} {3}", 
            addressTextBox.Text,
            cityTextBox.Text,
            stateTextBox.Text,
            zipTextBox.Text);
        Coordinate addressCoordinates = Geocode.GetCoordinates(address);

        // Only continue if the address actually has coordinates. If the coordinates are both ZERO, this means that 
        // Google Maps API could not find the address.
        if (addressCoordinates.Latitude != 0 && addressCoordinates.Longitude != 0)
        {
            SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["StoresDb"].ConnectionString);
            connection.Open();

            string SQL = "InsertLocation";
            SqlCommand command = new SqlCommand(SQL, connection);
            command.Parameters.Add(new SqlParameter("@locationName", locationNameTextBox.Text));
            command.Parameters.Add(new SqlParameter("@address", addressTextBox.Text));
            command.Parameters.Add(new SqlParameter("@city", cityTextBox.Text));
            command.Parameters.Add(new SqlParameter("@state", stateTextBox.Text));
            command.Parameters.Add(new SqlParameter("@zip", zipTextBox.Text));
            command.Parameters.Add(new SqlParameter("@latitude", addressCoordinates.Latitude));
            command.Parameters.Add(new SqlParameter("@longitude", addressCoordinates.Longitude));
            command.CommandType = CommandType.StoredProcedure;
            command.ExecuteNonQuery();

            resultsLiteral.Text = "Store Location Added."; 
        }
        else
        {
            resultsLiteral.Text = "Cannot verify address. Please verify address and try again."; 
        }
    }

    protected void ResetTextBoxes()
    {
        addressTextBox.Text = string.Empty;
        cityTextBox.Text = string.Empty;
        stateTextBox.Text = string.Empty;
        zipTextBox.Text = string.Empty;
        locationNameTextBox.Text = string.Empty; 
    }
    protected void resetButton_Click(object sender, EventArgs e)
    {
        ResetTextBoxes();
    }
}
